package com.yilife.kdys.service;

import com.yilife.kdys.JSONResult;
import com.yilife.kdys.RespStatusCode;
import com.yilife.kdys.mapper.MemberMapper;
import com.yilife.kdys.mapper.MemberProfileMapper;
import com.yilife.kdys.model.MemberBean;
import com.yilife.kdys.model.MemberProfileBean;
import com.yilife.kdys.model.request.RegisterRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by wuganlin on 2017/2/8.
 */
@Service
public class UserService {
    @Autowired
    private MemberProfileMapper memberProfileMapper;
    @Autowired
    private MemberMapper memberMapper;

    public JSONResult register(RegisterRequest req) {
        JSONResult result = new JSONResult();

        MemberProfileBean memberProfileBean = memberProfileMapper.searchByMobileName(req.getMobile(), req.getName());
        if (memberProfileBean != null) {
            result.setErrorcode(RespStatusCode.USERNAME_EXIST);
            result.setErrormsg("user exsits!");
            result.setData(memberProfileBean.member_id);
            return result;
        }

        if (req.getIdCard() != null) {
            if (memberMapper.searchByIdcard(req.getIdCard()) != null) {
                result.setErrormsg("身份证已经被使用了");
                result.setErrorcode(RespStatusCode.MEMBER_INVAILD);
                return result;
            }
        }

        MemberBean memberBean = new MemberBean();
        memberBean.password = req.getPassword();
        memberBean.mobile = req.getMobile();
        memberBean.idcard = req.getIdCard();
        memberBean.email = req.getEmail();
        memberBean.org_id = 26;
        memberMapper.insert(memberBean);

        memberProfileBean = new MemberProfileBean();
        memberProfileBean.member_id = memberBean.member_id;
        memberProfileBean.idcard = req.getIdCard();
        memberProfileBean.mobile = req.getMobile();
        memberProfileBean.name = req.getName();
        memberProfileBean.photo = req.getPhoto();
        memberProfileBean.gender = req.getGender();
        memberProfileBean.birthday = req.getBirthday();
        memberProfileBean.create_by = req.getCreatedBy();
        memberProfileMapper.insert(memberProfileBean);

        result.setErrorcode(RespStatusCode.SUCCESS);
        result.setErrormsg("Success");
        result.setData(memberBean.member_id);

        return result;
    }

    public JSONResult getUserInfo(int memberId) {
        JSONResult result = new JSONResult();
        MemberProfileBean memberProfileBean = memberProfileMapper.searchByMemberId(memberId);
        if (memberProfileBean == null) {
            result.setErrorcode(RespStatusCode.MEMBER_INVAILD);
            result.setErrormsg("MEMBER INVAILD");
            return result;
        }
        result.setErrorcode(RespStatusCode.SUCCESS);
        result.setErrormsg("Success");
        result.setData(memberProfileBean);
        return result;
    }
}
